package com.ssmTmp.api.web;


import com.ssmTmp.api.util.UserManage;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Component
@Aspect
@Slf4j
public class WebAspect {

    @Autowired
    private UserManage userManage;


    @Pointcut("execution(public * cn.com.ahsoft.zjmsa_oa.controller.*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {}

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {}

    //后置最终通知,final增强，不管是抛出异常或者正常退出都会执行
    @After("webLog()")
    public void after(JoinPoint jp)throws Throwable{}

    //环绕通知,环绕增强，相当于MethodInterceptor
    @Around("webLog()")
    public Object arround(ProceedingJoinPoint pjp) throws Throwable {
        TimesStatistics.begin();
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Object o =  pjp.proceed();
        Long times = TimesStatistics.end();
        if(times>=1000){//超过1秒
            log.warn("耗时:"+TimesStatistics.end()+";URL:"+request.getRequestURL().toString()+";HTTP_METHOD:"+request.getMethod());
        }else{
            //开发时打开
            log.info("耗时:"+TimesStatistics.end()+";URL:"+request.getRequestURL().toString()+";HTTP_METHOD:"+request.getMethod());
        }
        //userManage.remove();
        return o;

    }

}
